﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>2013-03-21 20:07:26Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using Microsoft.Phone.Shell;

namespace Outcoder.Services.Implementation
{
	public class TransientSettingsStore : ISettingsStore
	{
		IDictionary<string, object> stateDictionary_UseGetStateDictionary;

		IDictionary<string, object> GetStateDictionary()
		{
			if (stateDictionary_UseGetStateDictionary == null)
			{
				var service = PhoneApplicationService.Current;
				if (service == null || service.State == null)
				{
					return null;
				}

				stateDictionary_UseGetStateDictionary = service.State;
			}

			return stateDictionary_UseGetStateDictionary;
		}

		public SettingsStoreStatus Status
		{
			get
			{
				if (stateDictionary_UseGetStateDictionary == null)
				{
					GetStateDictionary();

					if (stateDictionary_UseGetStateDictionary == null)
					{
						return SettingsStoreStatus.Unavailable;
					}
				}

				return SettingsStoreStatus.Ready;
			}
		}

		public bool TryGetValue(string key, Type settingType, out object value)
		{
			var dictionary = GetStateDictionary();
			return dictionary.TryGetValue(key, out value);
		}

		public bool Contains(string key)
		{
			var dictionary = GetStateDictionary();
			return dictionary.ContainsKey(key);
		}

		public bool Remove(string key)
		{
			var dictionary = GetStateDictionary();
			return dictionary.Remove(key);
		}

		public async Task Clear()
		{
			var dictionary = GetStateDictionary();
			dictionary.Clear();
		}

		public async Task Save()
		{
			/* Nothing to do as this is handled by the phone OS. */
		}

		public object this[string key]
		{
			get
			{
				var dictionary = GetStateDictionary();
				return dictionary[key];
			}
			set
			{
				var dictionary = GetStateDictionary();
				dictionary[key] = value;
			}
		}
	}
}
